﻿using Dapper;
using System;
using BCEntity.Trading.Enquiry.SaleEnquiry;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCCommon;
using BCCommon.Extensions;

namespace BCData.Trading.Enquiry.SaleEnquiry
{
    /// <summary>
    /// 销售询盘
    /// </summary>
    public class SaleEnquiryData : ISaleEnquiryData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM saleenquiry";
        private const string QUERY = @"SELECT SaleEnquiryId,SaleEnquiryTitle,CustomerSexStr,SaleGoodsCategoryId,CategoryName,SaleGoodsId,GoodsName,SKU,NormName,NormNo,MainImage,SaleShoppingCartId,EnquiryMessage,EnquiryMode,EnquiryModeStr,EnquiryStatus,EnquiryStatusStr,ReceiptAdminId,ReceiptAdminName,ReceiptComments,FollowUpStartTime,TransferTime,UserId,TransferComments,CompleteEnquiryTime,CloseEnquiryTime,CloseEnquiryRemark,HasModifyPrice,CreateTime,UpdateTime,UserName,Phone,WeChatNo,CompanyName,CustomerAddress,CustomerSex FROM saleenquiry";
        public SaleEnquiryData(IDatabaseContext databaseContext)
        {
            this.databaseContext = databaseContext;
        }
        #region 检查销售询盘是否存在
        public async Task<bool> Exists(long saleEnquiryId)
        {
            string sql = string.Format(@"{0} WHERE SaleEnquiryId=?SaleEnquiryId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleEnquiryId", saleEnquiryId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }
        #endregion

        #region 添加销售询盘
        public async Task<SaleEnquiryEntity> Add(SaleEnquiryEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("saleenquiry", new string[] { "SaleEnquiryTitle", "CustomerSexStr", "SaleShoppingCartId", "EnquiryMessage", "EnquiryMode",
                "EnquiryModeStr", "EnquiryStatus", "EnquiryStatusStr", "ReceiptAdminId",
                "ReceiptAdminName", "ReceiptComments", "UserId", "UserName", "Phone", "WeChatNo", "CompanyName", "CustomerAddress", "CustomerSex" });
            sql = string.Format("{0} {1} WHERE SaleEnquiryId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleEnquiryTitle", entity.SaleEnquiryTitle, DbType.AnsiString, size: 30);
            parameters.Add("?CustomerSexStr", entity.CustomerSex.HasValue ? entity.CustomerSex.GetDisplayString() : null, DbType.AnsiString, size: 10);
            //parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            //parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            //parameters.Add("?SaleGoodsId", entity.SaleGoodsId, DbType.Int64, size: 20);
            //parameters.Add("?GoodsName", entity.GoodsName?.Trim(), DbType.AnsiString, size: 50);
            //parameters.Add("?SKU", entity.Sku?.Trim(), DbType.AnsiString, size: 50);
            //parameters.Add("?NormName", entity.NormName?.Trim(), DbType.AnsiString, size: 50);
            //parameters.Add("?NormNo", entity.NormNo?.Trim(), DbType.AnsiString, size: 100);
            //parameters.Add("?MainImage", entity.MainImage?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?SaleShoppingCartId", entity.SaleShoppingCartId, DbType.Int64, size: 20);
            parameters.Add("?EnquiryMessage", entity.EnquiryMessage?.Trim(), DbType.String);
            parameters.Add("?EnquiryMode", entity.EnquiryMode.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?EnquiryModeStr", entity.EnquiryMode.GetDisplayString(), DbType.AnsiString, size: 30);
            parameters.Add("?EnquiryStatus", entity.EnquiryStatus.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?EnquiryStatusStr", entity.EnquiryStatus.GetDisplayString(), DbType.AnsiString, size: 30);
            parameters.Add("?ReceiptAdminId", entity.ReceiptAdminId, DbType.Int64, size: 20);
            parameters.Add("?ReceiptAdminName", entity.ReceiptAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?ReceiptComments", entity.ReceiptComments?.Trim(), DbType.String);
            parameters.Add("?UserId", entity.UserId, DbType.Int64, size: 20);
            parameters.Add("?UserName", entity.UserName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?Phone", entity.Phone?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WeChatNo", entity.WeChatNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CompanyName", entity.CompanyName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?CustomerAddress", entity.CustomerAddress?.Trim(), DbType.AnsiString, size: 200);
            parameters.Add("?CustomerSex", entity.CustomerSex?.ToString(), DbType.AnsiString, size: 10);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleEnquiryEntity>(sql, parameters, databaseContext.Transaction);

        }
        #endregion

        #region 修改销售询盘
        public async Task<SaleEnquiryEntity> Update(SaleEnquiryEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("saleenquiry", new string[] {"SaleEnquiryTitle", "CustomerSexStr", "SaleShoppingCartId", "EnquiryMessage", "EnquiryMode", "EnquiryModeStr", "EnquiryStatus",
                "EnquiryStatusStr", "ReceiptAdminId", "ReceiptAdminName", "ReceiptComments", "FollowUpStartTime", "TransferTime", "UserId", "TransferComments", "CompleteEnquiryTime",
                "CloseEnquiryTime", "CloseEnquiryRemark", "HasModifyPrice", "UserName", "Phone", "WeChatNo", "CompanyName", "CustomerAddress", "CustomerSex" }, new string[] { "SaleEnquiryId" });
            sql = string.Format("{0} {1} WHERE SaleEnquiryId=?SaleEnquiryId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleEnquiryId", entity.SaleEnquiryId, DbType.Int64, size: 20);
            parameters.Add("?SaleEnquiryTitle", entity.SaleEnquiryTitle, DbType.AnsiString, size: 30);
            parameters.Add("?CustomerSexStr", entity.CustomerSex.HasValue ? entity.CustomerSex.GetDisplayString() : null, DbType.AnsiString, size: 10);
            //parameters.Add("?SaleGoodsCategoryId", entity.SaleGoodsCategoryId, DbType.Int64, size: 20);
            //parameters.Add("?CategoryName", entity.CategoryName?.Trim(), DbType.AnsiString, size: 10);
            //parameters.Add("?SaleGoodsId", entity.SaleGoodsId, DbType.Int64, size: 20);
            //parameters.Add("?GoodsName", entity.GoodsName?.Trim(), DbType.AnsiString, size: 50);
            //parameters.Add("?SKU", entity.Sku?.Trim(), DbType.AnsiString, size: 50);
            //parameters.Add("?NormName", entity.NormName?.Trim(), DbType.AnsiString, size: 50);
            //parameters.Add("?NormNo", entity.NormNo?.Trim(), DbType.AnsiString, size: 100);
            //parameters.Add("?MainImage", entity.MainImage?.Trim(), DbType.AnsiString, size: 1000);
            parameters.Add("?SaleShoppingCartId", entity.SaleShoppingCartId, DbType.Int64, size: 20);
            parameters.Add("?EnquiryMessage", entity.EnquiryMessage?.Trim(), DbType.String);
            parameters.Add("?EnquiryMode", entity.EnquiryMode.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?EnquiryModeStr", entity.EnquiryMode.GetDisplayString(), DbType.AnsiString, size: 30);
            parameters.Add("?EnquiryStatus", entity.EnquiryStatus.ToString(), DbType.AnsiString, size: 30);
            parameters.Add("?EnquiryStatusStr", entity.EnquiryStatus.GetDisplayString(), DbType.AnsiString, size: 30);
            parameters.Add("?ReceiptAdminId", entity.ReceiptAdminId, DbType.Int64, size: 20);
            parameters.Add("?ReceiptAdminName", entity.ReceiptAdminName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?ReceiptComments", entity.ReceiptComments?.Trim(), DbType.String);
            parameters.Add("?FollowUpStartTime", entity.FollowUpStartTime, DbType.DateTime);
            parameters.Add("?TransferTime", entity.TransferTime, DbType.DateTime);
            parameters.Add("?UserId", entity.UserId, DbType.Int64, size: 20);
            parameters.Add("?TransferComments", entity.TransferComments?.Trim(), DbType.String);
            parameters.Add("?CompleteEnquiryTime", entity.CompleteEnquiryTime, DbType.DateTime);
            parameters.Add("?CloseEnquiryTime", entity.CloseEnquiryTime, DbType.DateTime);
            parameters.Add("?CloseEnquiryRemark", entity.CloseEnquiryRemark?.Trim(), DbType.String);
            parameters.Add("?HasModifyPrice", entity.HasModifyPrice, DbType.Boolean);
            parameters.Add("?UserName", entity.UserName?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?Phone", entity.Phone?.Trim(), DbType.AnsiString, size: 20);
            parameters.Add("?WeChatNo", entity.WeChatNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?CompanyName", entity.CompanyName?.Trim(), DbType.AnsiString, size: 100);
            parameters.Add("?CustomerAddress", entity.CustomerAddress?.Trim(), DbType.AnsiString, size: 200);
            parameters.Add("?CustomerSex", entity.CustomerSex?.ToString(), DbType.AnsiString, size: 10);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<SaleEnquiryEntity>(sql, parameters, databaseContext.Transaction);
        }
        #endregion

        #region 删除销售询盘
        public async Task<bool> Delete(long saleEnquiryId)
        {
            string sql = @"DELETE FROM saleenquiry WHERE SaleEnquiryId=?SaleEnquiryId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleEnquiryId", saleEnquiryId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }
        #endregion

        #region 获取销售询盘
        public async Task<SaleEnquiryEntity> GetEntity(long saleEnquiryId)
        {
            string sql = string.Format(@"{0} WHERE SaleEnquiryId=?SaleEnquiryId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?SaleEnquiryId", saleEnquiryId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<SaleEnquiryEntity>(sql, parameters);
        }
        #endregion

        #region 获取销售最新询盘
        public async Task<SaleEnquiryEntity> GetLatestEntity(string phone)
        {
            string sql = string.Format(@"{0} WHERE Phone=?Phone ORDER BY SaleEquiryId DESC LIMIT 1", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?Phone", phone, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<SaleEnquiryEntity>(sql, parameters);
        }
        #endregion

        #region 获取销售询盘分页
        public async Task<(IEnumerable<SaleEnquiryEntity>, int)> Query(long? adminId, string userName, string phone, string companyName, string weChatNo, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (adminId.HasValue)
            {
                wheres.Add("ReceiptAdminId=?ReceiptAdminId");
                parameters.Add("?ReceiptAdminId", adminId, DbType.Int64);
            }
            if (!string.IsNullOrWhiteSpace(userName))
            {
                wheres.Add("UserName LIKE CONCAT('%',CONCAT(?UserName,'%'))");
                parameters.Add("?UserName", userName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(phone))
            {
                wheres.Add("Phone LIKE CONCAT('%',CONCAT(?Phone,'%'))");
                parameters.Add("?Phone", phone?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(companyName))
            {
                wheres.Add("CompanyName LIKE CONCAT('%',CONCAT(?CompanyName,'%'))");
                parameters.Add("?CompanyName", companyName?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(weChatNo))
            {
                wheres.Add("WeChatNo LIKE CONCAT('%',CONCAT(?WeChatNo,'%'))");
                parameters.Add("?WeChatNo", weChatNo?.Trim(), DbType.AnsiString);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM saleenquiry {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<SaleEnquiryEntity, int>(sql, parameters);
        }

        public async Task<(IEnumerable<SaleEnquiryEntity>, int)> Query(long userId, DateTime? start, DateTime? end, string sortName, bool? ascending, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            wheres.Add("UserId=?UserId");
            parameters.Add("?UserId", userId, DbType.Int64);
            
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY {4} {5} LIMIT {2},{3}; SELECT COUNT(1) FROM saleenquiry {1}",
                  QUERY,
                  wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                  (pageIndex == 0 ? 0 : pageIndex - 1) * pageSize,
                  pageSize,
                  string.IsNullOrWhiteSpace(sortName) ? "CreateTime" : sortName,
                  ascending.HasValue && ascending.Value ? "ASC" : "DESC");
            return await this.databaseContext.Slave.QueryMultipleAsync<SaleEnquiryEntity, int>(sql, parameters);
        }
        #endregion
    }
}



